package com.karrysong.blog_springboot.handle;

/**
 * @ClassName: LoginInterceptor
 * @Author: KarrySong
 * @Date: 2022/8/5 8:50
 * @Description:
 */
import com.alibaba.fastjson.JSON;
import com.karrysong.blog_springboot.entity.User;
import com.karrysong.blog_springboot.enums.ErrorCode;
import com.karrysong.blog_springboot.service.UserService;
import com.karrysong.blog_springboot.util.UserThreadLocal;
import com.karrysong.blog_springboot.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        if (!(handler instanceof HandlerMethod)){
            return true;
        }
        String token = request.getHeader("Authorization");
        log.info("=================request start===========================");
        String requestUri = request.getRequestURI();
        log.info("request uri:{}",requestUri);
        log.info("request method:{}",request.getMethod());
        log.info("token:{}", token);
        log.info("=================request end===========================");

        if (token == null){
            Result result = Result.fail(ErrorCode.NO_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        User sysUser = userService.checkToken(token);
        if (sysUser == null){
            Result result = Result.fail(ErrorCode.NO_LOGIN);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }

        //权限验证
        if (requestUri.contains("/admin") && sysUser.getAdmin() < 1){
            Result result = Result.fail(ErrorCode.NO_PERMISSION);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }

        //是登录状态，放行

        //我希望在controller中 直接获取用户的信息 怎么获取?
        UserThreadLocal.put(sysUser);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }

}

